package com.hxzy.config.security;

import com.hxzy.common.enums.AckCode;
import com.hxzy.entity.MallAdminUser;
import com.hxzy.exception.ServiceException;
import com.hxzy.service.MallAdminUserService;
import com.hxzy.service.SysMenuService;
import com.hxzy.service.SysRoleService;
import com.hxzy.vo.AdminLoginVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * spring security 自定义数据库查询实现
 * 功能描述
 *
 * @author tonneyyy
 */
@Log4j2
@Component
public class NewbeeUserDetailServiceImpl implements UserDetailsService{

    @Autowired
    private MallAdminUserService mallAdminUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        MallAdminUser dbUser=this.mallAdminUserService.findByLoginName(username);
        if(dbUser==null){
            log.error(username+","+ AckCode.USER_NOT_FOUND.getMsg());
            throw new ServiceException(AckCode.LOGIN_ACCOUNT_PASSWORD_ERROR);
        }
        //密码判断，不需要，因为DaoAuthenticationProvider 类 additionalAuthenticationChecks方法帮我们检查 密码是否一致
        //抛出BadCredentialsException这个异常   在springmvc全局异常处理中抓捕 AuthenticationException 异常就可以了

        //账号状态
        if(dbUser.getLocked().equals("1")){
            log.error(username+","+AckCode.DEVICE_BANNED.getMsg());
            throw new ServiceException(AckCode.DEVICE_BANNED);
        }

        //查询该用户拥有角色
        Set<String> ownRoleSet=this.sysRoleService.findRoleKeyByAdminId(dbUser.getAdminId());

        //查询该用户拥有菜单有哪些
        Set<String> permissSet=new HashSet<>();

        //超级管理员,拥有所有权限
        if(ownRoleSet.contains("admin")){
            permissSet.add("*:*:*");
        }else{
            // 普通 角色 查询它拥有的权限
            permissSet=this.sysMenuService.findMenuPermsByAdminId(dbUser.getAdminId());
        }
        // 实例化一个  UserDetails的接口的子类
        AdminLoginVO adminLoginVO=new AdminLoginVO(dbUser,ownRoleSet,permissSet);

        return adminLoginVO;
    }
}
